/**
 * MIT License
 *
 * Copyright (c) 2024 lishengbo
 * Email: 397237738@qq.com
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.open.cobertura.core.instrument;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Opentester-cobertura插桩类入口
 */
public class CoberturaInstrumenter {


    /**
     * 给类进行插桩
     * @param classFile
     * @return 字节码是用于后面适配agent的
     */
    public byte[] instrument(final String classFile,final String outClassFile){
        byte[] modifiedClassBytes=null;
        // 读取.class文件
        ClassReader cr = null;
        try {
            //1.获取Class文件 在agent中需要使用className
            FileInputStream fis = new FileInputStream(classFile);
            cr = new ClassReader(fis);
            ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
//            ClassWriter cw = new ClassWriter(cr, ClassReader.EXPAND_FRAMES);
            //CoberturaClassProbeVisitor->CoberturaMethodProbeVisitor
            CoberturaClassProbeVisitor couberturaClassProbeVisitor=new CoberturaClassInstrumenter(Opcodes.ASM9,cw);
            CoberturaClassProbeAdapter classFieldProbeArrayStub=new CoberturaClassProbeAdapter(Opcodes.ASM9,couberturaClassProbeVisitor);
            // 使用ClassVisitor来修改类
            //cr.accept(couberturaClassProbeVisitor, 0);
            cr.accept(classFieldProbeArrayStub,0);
            // 获取修改后的类字节码
            modifiedClassBytes = cw.toByteArray();
            // 将修改后的类写入到文件系统中
            try (FileOutputStream fos = new FileOutputStream(outClassFile)) {
                fos.write(modifiedClassBytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Field added successfully!");
        return modifiedClassBytes;
    }
}
